<template>
  <div class="map-container" :style="{width:containerWidth}">
    <div :id="mapId" :style="'height:'+height+'px'">
    </div>
  </div>
</template>

<script>
export default {
  name: 'MapBaidu',
  components: {},
  props: {
    mapKey: {
      type: String,
      default: '07E2669c3b77a0793274952ba61cd8b8'
    },
    keywordId: {
      type: String,
      required: true,
      default: ''
    },
    id: {
      type: String,
      default: function () {
        return 'vue-map-baidu-' + +new Date() + ((Math.random() * 1000).toFixed(0) + '')
      }
    },
    addressDetail: {
      type: Object,
      default() {
        return {
          province: '',
          provinceCode: '0',
          city: '',
          cityCode: '0',
          district: '',
          districtCode: '0',
          longitude: '',
          latitude: ''
        }
      }
    },
    height: {
      type: [Number, String],
      required: false,
      default: 400
    },
    width: {
      type: [Number, String],
      required: false,
      default: '100%'
    }
  },
  data() {
    return {
      mapId: this.id,
      lng: '',
      lat: ''
    }
  },
  computed: {
    containerWidth() {
      const width = this.width
      if (/^[\d]+(\.[\d]+)?$/.test(width)) { // matches `100`, `'100'`
        return `${width}px`
      }
      return width
    }
  },
  watch: {
    addressDetail: function (val, oldval) {
      //console.log(val, oldval)
    },
    'addressDetail.longitude': function (val, oldval) {
      this.addressDetail.longitude = val
    },
    'addressDetail.latitude': function (val, oldval) {
      this.addressDetail.latitude = val
    }
  },
  created() {
  },
  mounted() {
    this.init()
  },
  activated() {

  },
  deactivated() {

  },
  destroyed() {

  },
  methods: {
    init() {
      this.loadScript()
    },
    loadScript() {
      let that = this
      const script = document.createElement('script')
      window.initMap = () => {
        if (that.addressDetail.longitude && that.addressDetail.latitude) {
          that.initLocalCity()
        } else {
          that.initLocalPoint()
        }
      }
      script.type = 'text/javascript'
      script.src = 'https://api.map.baidu.com/api?v=2.0&ak=' + this.mapKey + '&callback=initMap'
      document.body.appendChild(script)
      script.onload = function () {
        /*setTimeout(() => {
          if (that.addressDetail.longitude && that.addressDetail.latitude) {
            that.initLocalCity()
          } else {
            that.initLocalPoint()
          }
        }, 1000)*/
      }
    },
    initBaidu(point) {
      const _this = this
      let map = new BMap.Map(this.mapId)
      // 鼠标滚动缩放
      map.enableScrollWheelZoom(false)
      // 初始化地图,设置中心点坐标和地图级别
      map.centerAndZoom(point, 16)
      // 添加中心小红点
      let centerPoint = new BMap.Marker(point)
      map.addOverlay(centerPoint)

      // 地图点击事件。获取点击位置经纬度位置
      map.addEventListener('click', function (e) {
        _this.lng = e.point.lng
        _this.lat = e.point.lat
        map.clearOverlays()
        map.addOverlay(new BMap.Marker(e.point))
        let point = new BMap.Point(e.point.lng, e.point.lat)
        // 地址解析类
        let geo = new BMap.Geocoder()
        geo.getLocation(point, function (rs) {
          let addressComp = rs.addressComponents
          _this.addressDetail.province = addressComp.province
          _this.addressDetail.city = addressComp.city
          _this.addressDetail.district = addressComp.district
        })
      })

      // 建立一个自动完成的对象，keyword出现下拉选择
      let ac = new BMap.Autocomplete({
        'input': this.keywordId, // input 搜索
        'location': map
      })
      ac.setInputValue('')
      // 鼠标点击下拉列表后的事件
      ac.addEventListener('onconfirm', function (e) {
        let thisValue = e.item.value
        let thisProvince = thisValue.province
        let thisCity = thisValue.city
        let thisDistrict = thisValue.district
        let thisStreet = thisValue.street
        let thisStreetNumber = thisValue.streetNumber
        let thisBusiness = thisValue.business
        let thisKey = thisProvince + thisCity + thisDistrict + thisStreet + thisStreetNumber + thisBusiness

        _this.searchByKey(map, thisKey, centerPoint)
      })
    },
    //  输入关键字搜索，根据关键字更新地图并获取信息
    searchByKey(map, keyword, centerPoint) {
      const _this = this;
      let localSearch = new BMap.LocalSearch(map)
      localSearch.enableAutoViewport()
      localSearch.search(keyword)
      localSearch.setSearchCompleteCallback(function (searchResult) {
        if (searchResult && searchResult.getPoi(0)) {
          var poi = searchResult.getPoi(0);
          if (poi.point) {
            map.centerAndZoom(poi.point, 16)
            centerPoint.setPosition(poi.point)

            var myGeo = new BMap.Geocoder()
            myGeo.getLocation(poi.point, function (result) {
              _this.callBack(result)
            })
          }
        }
      })
    },
    // 地图拖拽后 和 输入关键字后选择 的回调函数
    callBack(result, tag) {
      const _this = this
      let thisAddress = result.addressComponents
      if (thisAddress.province == '新疆维吾尔自治区' || thisAddress.province == '西藏自治区') {
        console.log('很抱歉，新疆和西藏地区暂不支持该服务，敬请期待。')
      } else {
        _this.addressDetail.province = thisAddress.province
        _this.addressDetail.city = thisAddress.city
        _this.addressDetail.district = thisAddress.district
        _this.addressDetail.longitude = result.point.lng
        _this.addressDetail.latitude = result.point.lat
      }

      this.mapCBK()
    },
    // 初始化当前城市
    initLocalCity() {
      let point = new BMap.Point(this.addressDetail.longitude, this.addressDetail.latitude)
      this.initBaidu(point)
    },
    // 初始化当前位置(浏览器定位)
    initLocalPoint() {
      const that = this
      let geolocation = new BMap.Geolocation()
      geolocation.getCurrentPosition(function (position) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
          // 根据浏览器定位,设置城市和地图级别
          that.initBaidu(position.point)
        }
      })
    },

    // 回调
    mapCBK() {
      this.$emit('mapCallback', this.addressDetail)
    }
  }
}
</script>

<style lang="scss">
.tangram-suggestion-main {
  z-index: 999999;
}
</style>
